//
//  WebViewController.m
//  iMiniTao
//
//  Created by liunian on 13-8-19.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "WebViewController.h"
#import "LocalSubstitutionCache.h"
#import "MBButtonMenuViewController.h"
#import <QuartzCore/QuartzCore.h>

@interface WebViewController ()<UIWebViewDelegate,MFMailComposeViewControllerDelegate,MBButtonMenuViewControllerDelegate>
@property (nonatomic, retain) NSURL *URL;
@property (nonatomic, retain) UIImageView *topView;
@property (nonatomic, retain) UIWebView *webView;
@property (nonatomic, retain) UILabel *name;

@property (nonatomic, retain) UIButton *backBtn;
@property (nonatomic, retain) UIButton *forwardBtn;
@property (nonatomic, retain) UIButton *refreshBtn;
@property (nonatomic, retain) UIButton *shareBtn;
@property (nonatomic, retain) MBButtonMenuViewController *menu;
@end

@implementation WebViewController
- (void)dealloc{
    _webView.delegate = nil;
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
- (id)initWithURL:(NSURL*)pageURL {
    
    if(self = [super init]) {
        self.URL = pageURL;
        LocalSubstitutionCache *urlCache = [[LocalSubstitutionCache alloc] initWithMemoryCapacity:20 * 1024 * 1024
                                                                                     diskCapacity:200 * 1024 * 1024
                                                                                         diskPath:nil
                                                                                        cacheTime:0];
        [LocalSubstitutionCache setSharedURLCache:urlCache];
    }
    
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
#if __IPHONE_OS_VERSION_MAX_ALLOWED < 70000
    {
    }
#else
    float systemName = [[[UIDevice currentDevice] systemVersion] floatValue];
    if(systemName >= 7.0)
    {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
    }
#endif
    
    [self.name setText:@"浏览"];
    [self.webView setBackgroundColor:[UIColor whiteColor]];
    [self.webView loadRequest:[NSURLRequest requestWithURL:self.URL]];
    
    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame: CGRectMake(0, CGRectGetHeight(self.view.bounds) - 49, CGRectGetWidth(self.view.bounds), 49)];
    toolbar.barStyle = UIBarStyleDefault;
    UIImage *image = [UIImage imageNamed:@"bottomTabBarBackground.png"];
    [toolbar setBackgroundImage:image  forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
    toolbar.alpha = 1;
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:self.backBtn];
    UIBarButtonItem *forwardItem = [[UIBarButtonItem alloc] initWithCustomView:self.forwardBtn];
    UIBarButtonItem *refreshItem = [[UIBarButtonItem alloc] initWithCustomView:self.refreshBtn];
    UIBarButtonItem *shareItem = [[UIBarButtonItem alloc] initWithCustomView:self.shareBtn];
    
    UIBarButtonItem *flexibleItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
    [toolbar setItems: [[NSArray alloc] initWithObjects: backItem, flexibleItem, refreshItem,flexibleItem, shareItem, flexibleItem, forwardItem, nil]];
    
    [self.view addSubview:toolbar];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    LocalSubstitutionCache *urlCache = (LocalSubstitutionCache *)[NSURLCache sharedURLCache];
    [urlCache removeAllCachedResponses];
}

- (void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden = YES;
}
#if __IPHONE_OS_VERSION_MAX_ALLOWED < 70000

#else
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDefault;
}
#endif
- (void)updateToolbarItems{
    self.backBtn.enabled = self.webView.canGoBack;
    self.forwardBtn.enabled = self.webView.canGoForward;
    self.shareBtn.enabled = !self.webView.isLoading;
}

#pragma mark -
#pragma mark UIWebViewDelegate

- (void)webViewDidStartLoad:(UIWebView *)webView {
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    [self updateToolbarItems];
}


- (void)webViewDidFinishLoad:(UIWebView *)webView {
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    self.name.text = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    [self updateToolbarItems];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    [self updateToolbarItems];
}
#pragma mark - MBButtonMenuViewControllerDelegate
- (void)buttonMenuViewController:(MBButtonMenuViewController *)buttonMenu buttonTappedAtIndex:(NSUInteger)index
{
    [buttonMenu hide];
    switch (index) {
        case 0:
        {
            [[UIApplication sharedApplication] openURL:self.webView.request.URL];
        }
            break;
        case 1:
        {
            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
            pasteboard.string = self.webView.request.URL.absoluteString;
        }
            break;
        case 2:
        {
            MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
            
            mailViewController.mailComposeDelegate = self;
            [mailViewController setSubject:[self.webView stringByEvaluatingJavaScriptFromString:@"document.title"]];
            [mailViewController setMessageBody:self.webView.request.URL.absoluteString isHTML:NO];
            mailViewController.modalPresentationStyle = UIModalPresentationFormSheet;
            
            [self presentViewController:mailViewController animated:YES completion:nil];
        }
            break;
        default:
            break;
    }
    
}

- (void)buttonMenuViewControllerDidCancel:(MBButtonMenuViewController *)buttonMenu{
    [buttonMenu hide];
}
#pragma mark MFMailComposeViewControllerDelegate
- (void)mailComposeController:(MFMailComposeViewController *)controller
          didFinishWithResult:(MFMailComposeResult)result
                        error:(NSError *)error
{
	[self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark action
- (void)back{
    [self.webView goBack];
}
- (void)forward{
    [self.webView goForward];
}
- (void)refresh{
    [self.webView reload];
}
- (void)share{
    [self.menu showInView:self.view];
}
- (void)backParentController{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark
- (UILabel *)name{
    if (!_name) {
        _name = [[UILabel alloc] initWithFrame:CGRectMake(40, 10, 240, 24)];
        [_name setBackgroundColor:[UIColor clearColor]];
        [_name setTextColor:[UIColor darkTextColor]];
        [_name setNumberOfLines:1];
        [_name setTextAlignment:[Util getAlign:ALIGNTYPE_CENTER]];
        [_name setFont:[UIFont fontWithName:@"FZLTHJW.TTF" size:16]];
        [_name setFont:[UIFont boldSystemFontOfSize:16]];
        [self.topView addSubview:_name];
    }
    return _name;
}

- (UIImageView *)topView{
    if (!_topView) {
        _topView = [[UIImageView alloc] initWithFrame:CGRectMake(0, _kSpaceHeight, CGRectGetWidth(self.view.bounds), 44)];
        [_topView setBackgroundColor:[UIColor whiteColor]];
        [_topView setImage:IMGNAMED(@"categorySearchBarBackground.png.png")];
        [_topView setUserInteractionEnabled:YES];
        UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [backBtn setFrame:CGRectMake(10, 5, 30, 30)];
        [backBtn setImage:IMGNAMED(@"News_Arrow.png") forState:UIControlStateNormal];
        [backBtn setImage:IMGNAMED(@"News_Arrow_Highlight.png") forState:UIControlStateHighlighted];
        [backBtn addTarget:self action:@selector(backParentController) forControlEvents:UIControlEventTouchUpInside];
        [_topView addSubview:backBtn];
        [self.view addSubview:_topView];
    }
    return _topView;
}

- (UIWebView *)webView{
    if (nil == _webView) {
        _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.topView.frame), CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) - 44 - 44 -_kSpaceHeight)];
        _webView.scalesPageToFit = YES;
        _webView.delegate = self;
        _webView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        _webView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        [self.view addSubview:_webView];
    }
    return _webView;
}
- (UIButton *)backBtn{
    if (!_backBtn) {
        _backBtn = [UIButton buttonWithType: UIButtonTypeCustom];
        _backBtn.frame = CGRectMake(0, 0, 30, 30);
        [_backBtn setImage: [UIImage imageNamed: @"Browser_Icon_Back.png"] forState: UIControlStateNormal];
        [_backBtn setImage: [UIImage imageNamed: @"Browser_Icon_Back_Highlight.png"] forState: UIControlStateHighlighted];
        [_backBtn setImage: [UIImage imageNamed: @"Browser_Icon_Back_Disable.png"] forState: UIControlStateDisabled];
        [_backBtn addTarget: self action: @selector(back) forControlEvents: UIControlEventTouchUpInside];
    }
    return _backBtn;
}

- (UIButton *)forwardBtn{
    if (!_forwardBtn) {
        _forwardBtn = [UIButton buttonWithType: UIButtonTypeCustom];
        _forwardBtn.frame = CGRectMake(0, 0, 30, 30);
        [_forwardBtn setImage: [UIImage imageNamed: @"Browser_Icon_Forward.png"] forState: UIControlStateNormal];
        [_forwardBtn setImage: [UIImage imageNamed: @"Browser_Icon_Forward_Highlight.png"] forState: UIControlStateHighlighted];
        [_forwardBtn setImage: [UIImage imageNamed: @"Browser_Icon_Forward_Disable.png"] forState: UIControlStateDisabled];
        
        [_forwardBtn addTarget: self action: @selector(forward) forControlEvents: UIControlEventTouchUpInside];
    }
    return _forwardBtn;
}

- (UIButton *)refreshBtn{
    if (!_refreshBtn) {
        _refreshBtn = [UIButton buttonWithType: UIButtonTypeCustom];
        _refreshBtn.frame = CGRectMake(0, 0, 30, 30);
        [_refreshBtn setImage: [UIImage imageNamed: @"Browser_Icon_Reload.png"] forState: UIControlStateNormal];
        [_refreshBtn setImage: [UIImage imageNamed: @"Browser_Icon_Reload_Highlight.png"] forState: UIControlStateHighlighted];
        [_refreshBtn setImage: [UIImage imageNamed: @"Browser_Icon_Reload.png"] forState: UIControlStateDisabled];
        
        [_refreshBtn addTarget: self action: @selector(refresh) forControlEvents: UIControlEventTouchUpInside];
    }
    return _refreshBtn;
}

- (UIButton *)shareBtn{
    if (!_shareBtn) {
        _shareBtn = [UIButton buttonWithType: UIButtonTypeCustom];
        _shareBtn.frame = CGRectMake(0, 0, 30, 30);
        [_shareBtn setImage: [UIImage imageNamed: @"Browser_Icon_Action.png"] forState: UIControlStateNormal];
        [_shareBtn setImage: [UIImage imageNamed: @"Browser_Icon_Action_Highlight.png"] forState: UIControlStateHighlighted];
        [_shareBtn addTarget: self action: @selector(share) forControlEvents: UIControlEventTouchUpInside];
    }
    return _shareBtn;
}
- (MBButtonMenuViewController *)menu{
    if (nil == _menu) {
        NSArray *titles = [NSArray arrayWithObjects:@"在Safari中打开",
                           @"拷贝该页网址",
                           @"邮件发送该网址",
                           @"取消", nil];
        _menu = [[MBButtonMenuViewController alloc] init];
        [_menu setButtonTitles:titles];
        [_menu setDelegate:self];
        [_menu setCancelButtonIndex:[[_menu buttonTitles] count]-1];
    }
    return _menu;
}

@end
